

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blog/img/fluid.png">
  <link rel="icon" href="/blog/images/base.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Airfe">
  <meta name="keywords" content="">
  
    <meta name="description" content="本文将介绍Javascript的一种常用优秀的异步解决方案Promise。">
<meta property="og:type" content="article">
<meta property="og:title" content="异步编程（一）Promise">
<meta property="og:url" content="https://airfe.gitee.io/blog/2023/05/17/%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%EF%BC%88%E4%B8%80%EF%BC%89Promise/index.html">
<meta property="og:site_name" content="Airfe的博客">
<meta property="og:description" content="本文将介绍Javascript的一种常用优秀的异步解决方案Promise。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/pageImage/JavaScript%E5%87%BD%E6%95%B0.png">
<meta property="article:published_time" content="2023-05-17T00:00:00.000Z">
<meta property="article:modified_time" content="2024-02-26T12:25:10.452Z">
<meta property="article:author" content="Airfe">
<meta property="article:tag" content="js">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/pageImage/JavaScript%E5%87%BD%E6%95%B0.png">
  
  
  
    <meta name="referrer" content="no-referrer" />
  
  <title>异步编程（一）Promise - Airfe的博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"airfe.gitee.io","root":"/blog/","version":"1.9.4","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":"699a5d71ac7179b23874a59b0666a6f6","google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","app_key":"P5fzMTGSJIoTaGvmgzsUHeNZ","server_url":"https://rw68dmke.lc-cn-n1-shared.com","path":"window.location.pathname","ignore_local":false}},"search_path":"/blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/blog/js/utils.js" ></script>
  <script  src="/blog/js/color-schema.js" ></script>
  

  
    <!-- Baidu Analytics -->
    <script async>
      if (!Fluid.ctx.dnt) {
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?699a5d71ac7179b23874a59b0666a6f6";
          var s = document.getElementsByTagName("script")[0];
          s.parentNode.insertBefore(hm, s);
        })();
      }
    </script>
  

  

  

  

  

  

  
    
  



  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/blog/">
      <strong>Airfe</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/links/">
                <i class="iconfont icon-link-fill"></i>
                <span>友链</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/blog/images/bg.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="异步编程（一）Promise"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-05-17 08:00" pubdate>
          2023年05月17日
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          8.6k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          72 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">异步编程（一）Promise</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="同步和异步"><a href="#同步和异步" class="headerlink" title="同步和异步"></a>同步和异步</h1><p>同步：对应内存中<strong>顺序执行</strong>的处理器指令。</p>
<p>异步：类似于系统中断，即当前进程 外部的实体可以触发代码执行。（异步代码内部还没执行，下面的同步代码已经执行了）</p>
<p>异步操作经常是必要的，因为强制进程等待一个长时间的操作通常是不可行的。</p>
<h1 id="以往的异步编程"><a href="#以往的异步编程" class="headerlink" title="以往的异步编程"></a>以往的异步编程</h1><p>异步代码的返回值，只能在异步代码执行结束之后调用回调函数传递。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">YiBu</span>(<span class="hljs-params">callback</span>)&#123;<br>    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>        <span class="hljs-keyword">let</span> x = <span class="hljs-number">1</span>+<span class="hljs-number">1</span><br>        <span class="hljs-title function_">callback</span>(x)<br>    &#125;,<span class="hljs-number">1000</span>);<br>&#125;<br><span class="hljs-keyword">function</span> <span class="hljs-title function_">someFunc</span>(<span class="hljs-params">x</span>)&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x)<br>&#125;<br><span class="hljs-title class_">YiBu</span>(someFunc)<br></code></pre></td></tr></table></figure>

<p>异步代码的异常处理</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">YiBu</span>(<span class="hljs-params">callback</span>)&#123;<br>    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>        <span class="hljs-keyword">try</span>&#123;<br>             <span class="hljs-keyword">let</span> x = <span class="hljs-number">1</span>+<span class="hljs-number">1</span><br>             <span class="hljs-title function_">callback</span>(x)<br>        &#125;<span class="hljs-keyword">catch</span>(e)&#123;<br>            <span class="hljs-comment">// 异常处理</span><br>            <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;出现问题啦&#x27;</span>)<br>        &#125;<br>    &#125;,<span class="hljs-number">1000</span>);<br>&#125;<br><span class="hljs-keyword">function</span> <span class="hljs-title function_">someFunc</span>(<span class="hljs-params">x</span>)&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x)<br>&#125;<br><span class="hljs-title class_">YiBu</span>(someFunc)<br></code></pre></td></tr></table></figure>

<p>异步代码的嵌套（包括各级的异常处理）</p>
<p>嵌套层级的不断增加&#x3D;&#x3D;&#x3D;&gt;<strong>回调地域</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">YiBu</span>(<span class="hljs-params">callback</span>)&#123;<br>    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>        <span class="hljs-keyword">try</span>&#123;<br>             <span class="hljs-keyword">let</span> x = <span class="hljs-number">1</span>+<span class="hljs-number">1</span><br>             <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>                 <span class="hljs-keyword">try</span>&#123;<br>                     <span class="hljs-title function_">callback</span>(x)<br>                 &#125;<span class="hljs-keyword">catch</span>(e)&#123;<br>                     <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;出现问题2&#x27;</span>)<br>                 &#125;<br>             &#125;,<span class="hljs-number">2000</span>)<br>        &#125;<span class="hljs-keyword">catch</span>(e)&#123;<br>            <span class="hljs-comment">// 异常处理</span><br>            <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;出现问题1&#x27;</span>)<br>        &#125;<br>    &#125;,<span class="hljs-number">1000</span>);<br>&#125;<br><span class="hljs-keyword">function</span> <span class="hljs-title function_">someFunc</span>(<span class="hljs-params">x</span>)&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x)<br>&#125;<br><span class="hljs-title class_">YiBu</span>(someFunc)<br></code></pre></td></tr></table></figure>

<h1 id="Promise"><a href="#Promise" class="headerlink" title="Promise"></a>Promise</h1><h2 id="什么是promise"><a href="#什么是promise" class="headerlink" title="什么是promise"></a>什么是promise</h2><p>是现在Javascript的一种常用优秀的异步解决方案，以前我们需要拿到异步代码的返回值，只能在异步代码里面调回调函数，如果回调函数里面又有异步代码就又有回调函数，不断的嵌套，就会形成俗称的回调地域。promise就可以很好地解决这个问题。</p>
<p>其他常用的异步方案还有async&#x2F;await。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 入参是一个执行器，返回一个默认为pending状态的promise实例</span><br><span class="hljs-comment">// 入参不填会报错 let a = new Promise()报错</span><br><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(  <span class="hljs-function">()=&gt;</span>&#123;&#125;  )<br></code></pre></td></tr></table></figure>

<p>期约的主要两大用途：知道异步代码的执行情况（状态）、实际生成某个值。</p>
<h2 id="promise状态"><a href="#promise状态" class="headerlink" title="promise状态"></a>promise状态</h2><p>每一个  Promise的实例都有一个状态，一共有三种状态。</p>
<ul>
<li>resolved（解决）</li>
<li>rejected（拒绝）</li>
<li>pending（待定）</li>
</ul>
<p>在待定状态下，期约可以落定为代表成功或者失败的状态，无论落定为哪种状态都是<strong>不可逆</strong>的。</p>
<p>在执行器函数内部调用内置的resolve()和reject()函数可以改变Promise的状态，同时也可以传递参数，这个参数就叫做<strong>解决值&#x2F;拒绝值</strong>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> p1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-string">&#x27;data&#x27;</span>));<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(p1) <span class="hljs-comment">// Promise &#123; &#x27;data&#x27; &#125;   此时已经是&lt;resolved&gt;状态</span><br></code></pre></td></tr></table></figure>

<blockquote>
<p>外部的同步代码无法读取或修改期约的状态，异步代码只能通过期约的方法（异步结构）与之交互。</p>
</blockquote>
<h2 id="执行器"><a href="#执行器" class="headerlink" title="执行器"></a>执行器</h2><p>执行器的作用如下</p>
<ul>
<li><p>初始化Promise的行为</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;初始化行为&#x27;</span>)<br>    <span class="hljs-comment">// 这里要做啥</span><br>&#125;)<br></code></pre></td></tr></table></figure>
</li>
<li><p>控制Promise的状态转换（通过调用两个函数参数实现）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve,reject</span>)=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;初始化行为&#x27;</span>)<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-number">1</span>+<span class="hljs-number">1</span>)<br>    <br>    <span class="hljs-comment">//做完以后，让promise状态变为已解决</span><br>    <span class="hljs-title function_">resolve</span>(<span class="hljs-string">&#x27;这条代码已解决，我是解决值&#x27;</span>)<br>&#125;)<br><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a) <span class="hljs-comment">// 初始化行为  2  Promise&#123;&#x27;这条代码已解决&#x27;&#125;</span><br></code></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve,reject</span>)=&gt;</span>&#123;<br>    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>        <span class="hljs-comment">// 随便写个定时器</span><br>        <span class="hljs-comment">// 诶定时完了我让他变状态也可以</span><br>    	<span class="hljs-title function_">resolve</span>(<span class="hljs-string">&#x27;我是解决值&#x27;</span>)<br>	&#125;,<span class="hljs-number">200000</span>);<br>&#125;)<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a)<br></code></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 调接口拿值</span><br><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve,reject</span>)=&gt;</span>&#123;<br>    <span class="hljs-keyword">var</span> xhr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">XMLHttpRequest</span>();<br>    xhr.<span class="hljs-property">onreadystatechange</span> = <span class="hljs-function">() =&gt;</span>&#123;<br>        <span class="hljs-keyword">if</span>(xhr.<span class="hljs-property">readyState</span>!=<span class="hljs-number">4</span>) <span class="hljs-keyword">return</span>;<br>        <span class="hljs-keyword">if</span>(xhr.<span class="hljs-property">readyState</span>==<span class="hljs-number">4</span> &amp;&amp; xhr.<span class="hljs-property">status</span> ==<span class="hljs-number">200</span>) &#123;<br>            <span class="hljs-comment">// 请求成功时改变Promise状态</span><br>            <span class="hljs-title function_">resolve</span>(xhr.<span class="hljs-property">responsetext</span>)  <span class="hljs-comment">//解决值</span><br>        &#125;<span class="hljs-keyword">else</span>&#123;<br>            <span class="hljs-comment">// 请求失败时改变Promise状态</span><br>            <span class="hljs-title function_">reject</span>(<span class="hljs-string">&#x27;服务器错误&#x27;</span>) <span class="hljs-comment">//拒绝值（拒绝原因）</span><br>        &#125;<br>    &#125;<br>    xhr.<span class="hljs-title function_">open</span>(<span class="hljs-string">&#x27;get&#x27;</span>,url);<br>    xhr.<span class="hljs-title function_">send</span>(<span class="hljs-literal">null</span>);<br>&#125;)<br><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a)<br></code></pre></td></tr></table></figure>
</li>
<li><p>注意</p>
<p>执行器函数是其实是同步的，也就是说执行器函数的代码是会比new…后面的代码先执行的</p>
<p>但是执行器函数里面允许异步代码，比如resolve()、reject()、setTimeout()</p>
<blockquote>
<p>直接抛出异常可以理解为执行失败&#x3D;拒绝&#x3D;reject()，故执行器里面直接抛出错误外面的同步代码是捕获不到的，只能通过异步结构拿到。</p>
<p>可以理解为异步代码是由一个函数包裹住的，里面的参数外面的代码都拿不到，只有函数内（异步代码）才可以取得。</p>
</blockquote>
<p>来看下面的例子</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve,reject</span>)=&gt;</span>&#123;<br>    <span class="hljs-comment">// 只是一个执行器</span><br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;我是来证明执行器是同步执行&#x27;</span>)<br>    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>         <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;promise执行器里有一个异步代码&#x27;</span>)<br>    	<span class="hljs-title function_">resolve</span>(<span class="hljs-string">&#x27;哈哈&#x27;</span>)<br>	&#125;,<span class="hljs-number">1000</span>);<br>&#125;)<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;我是同步代码&#x27;</span>)<br><br><span class="hljs-comment">// 打印结果：</span><br><span class="hljs-comment">// 我是来证明执行器是同步执行</span><br><span class="hljs-comment">// 我是同步代码</span><br><span class="hljs-comment">// promise执行器里有一个异步代码</span><br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="解决值和拒绝值"><a href="#解决值和拒绝值" class="headerlink" title="解决值和拒绝值"></a>解决值和拒绝值</h2><p>每个期约只要状态切换为兑现，就会有一个私有的内部值（value）。状态切换为拒绝，就会有一个私有的内部理由（reason）。无论是值还是理由，都是包含原始值或对象的不可修改的引用。二者都是可选的，而且默认值为 undefined。</p>
<blockquote>
<p>比如，假设期约向服务器发送一个 HTTP 请求并预定会返回一个 JSON。如果请求返回范围在 200<del>299 的状态码，则足以让期约的状态变为兑现。此时期约内部就可以收到一个 JSON 字符串。类似地，如果请求返回的状态码不在 200</del>299 这个范围内，那么就会把期约状态切换为拒绝。此时拒绝的理由可能是一个 Error对象，包含着 HTTP 状态码及相关错误消息。</p>
</blockquote>
<p>到了落定状态后，期约会提供其解决值（如果兑现）或其拒绝理由（如果拒绝）给相关状态的处理程序。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> p1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-string">&#x27;foo&#x27;</span>)); <br>p1.<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value)); <span class="hljs-comment">// foo </span><br><br><span class="hljs-keyword">let</span> p2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> <span class="hljs-title function_">reject</span>(<span class="hljs-string">&#x27;bar&#x27;</span>)); <br>p2.<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">reason</span>) =&gt;</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(reason)); <span class="hljs-comment">// bar</span><br></code></pre></td></tr></table></figure>

<h2 id="静态方法"><a href="#静态方法" class="headerlink" title="静态方法"></a>静态方法</h2><h3 id="Promise-resolve"><a href="#Promise-resolve" class="headerlink" title="Promise.resolve()"></a>Promise.resolve()</h3><p><strong>创建</strong>一个已经解决的<strong>Promise</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> p = <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">3</span>);<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(p)  <span class="hljs-comment">// Promise &#123; 3 &#125;</span><br><span class="hljs-comment">// 等价于</span><br><span class="hljs-keyword">let</span> p = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-number">3</span>));<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(p)<br></code></pre></td></tr></table></figure>

<p>入参是任意类型，返回值是一个Promise</p>
<p>转换规则：</p>
<ul>
<li><p>入参是基础数据类型</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> p1 = <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">1</span>);<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(p1)  <span class="hljs-comment">// Promise &#123; 1 &#125;</span><br></code></pre></td></tr></table></figure>

<p>返回值：一个<strong>解决值</strong>为这个<strong>基础值</strong>的<strong>已解决</strong>的<strong>Promise</strong></p>
</li>
<li><p>入参就是一个Promise</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> p1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">()=&gt;</span>&#123;&#125;)<br><span class="hljs-keyword">let</span> p2 = <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(p1);<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(p1)  <span class="hljs-comment">// Promise &#123;&lt;pengding&gt;&#125;</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(p2)  <span class="hljs-comment">// Promise &#123;&lt;pengding&gt;&#125;</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(p1===p2)  <span class="hljs-comment">// true</span><br></code></pre></td></tr></table></figure>

<p>返回值：直接返回入参的<strong>Promise</strong></p>
</li>
<li><p>入参是一个异常</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> p3 = <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">&#x27;&#x27;</span>));<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(p3)  <br><span class="hljs-comment">// Promise &#123;                                                                                     </span><br><span class="hljs-comment">//    Error                                                                                       </span><br><span class="hljs-comment">//        at Object.&lt;anonymous&gt; (D:\WebStorm\project\study\JS\期约与异步函数\src\异步函数.js:1:26)</span><br><span class="hljs-comment">//        at Module._compile (node:internal/modules/cjs/loader:1105:14)                           </span><br><span class="hljs-comment">//        at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)             </span><br><span class="hljs-comment">//        at Module.load (node:internal/modules/cjs/loader:981:32)                                </span><br><span class="hljs-comment">//        at Function.Module._load (node:internal/modules/cjs/loader:822:12)</span><br><span class="hljs-comment">//        at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)</span><br><span class="hljs-comment">//        at node:internal/main/run_main_module:17:47</span><br><span class="hljs-comment">//  &#125;</span><br></code></pre></td></tr></table></figure>

<p>返回值：一个<strong>解决值</strong>为<strong>这个异常</strong>的<strong>已解决</strong>的<strong>Promise</strong></p>
</li>
<li><p>多个参数</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> p4 = <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">1</span>,<span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">()=&gt;</span>&#123;&#125;),<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>());<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(p4)  <span class="hljs-comment">// Promise &#123; 1 &#125;</span><br></code></pre></td></tr></table></figure>

<p>返回值：把第一个参数按照上述规则包装返回</p>
</li>
</ul>
<h3 id="Promise-reject"><a href="#Promise-reject" class="headerlink" title="Promise.reject()"></a>Promise.reject()</h3><p>入参是任意类型，返回值是一个Promise</p>
<ul>
<li><p>入参是基础数据类型</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> p1 = <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(<span class="hljs-number">1</span>);<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(p1)  <span class="hljs-comment">// Promise &#123; &lt;rejected&gt; 1 &#125;</span><br></code></pre></td></tr></table></figure>

<p>返回值：一个<strong>拒绝值</strong>为这个<strong>基础值</strong>的<strong>已拒绝</strong>的<strong>Promise</strong></p>
</li>
<li><p>入参就是一个Promise</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> p1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">()=&gt;</span>&#123;&#125;)<br><span class="hljs-keyword">let</span> p2 = <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(p1);<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(p1)  <span class="hljs-comment">// Promise &#123;&lt;pengding&gt;&#125;</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(p2)  <span class="hljs-comment">// Promise &#123; &lt;rejected&gt; Promise &#123; &lt;pending&gt; &#125; &#125;</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(p1===p2)  <span class="hljs-comment">// false</span><br></code></pre></td></tr></table></figure>

<p>返回值：一个<strong>拒绝值</strong>为这个<strong>入参</strong>的<strong>已拒绝</strong>的<strong>Promise</strong></p>
</li>
<li><p>入参是一个异常</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> p3 = <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">&#x27;&#x27;</span>));<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(p3)  <br><span class="hljs-comment">// Promise &#123;                                                                                     </span><br><span class="hljs-comment">//    &lt;rejected&gt;  Error                                                                                       </span><br><span class="hljs-comment">//        at Object.&lt;anonymous&gt; (D:\WebStorm\project\study\JS\期约与异步函数\src\异步函数.js:1:26)</span><br><span class="hljs-comment">//        at Module._compile (node:internal/modules/cjs/loader:1105:14)                           </span><br><span class="hljs-comment">//        at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)             </span><br><span class="hljs-comment">//        at Module.load (node:internal/modules/cjs/loader:981:32)                                </span><br><span class="hljs-comment">//        at Function.Module._load (node:internal/modules/cjs/loader:822:12)</span><br><span class="hljs-comment">//        at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)</span><br><span class="hljs-comment">//        at node:internal/main/run_main_module:17:47</span><br><span class="hljs-comment">//  &#125;</span><br></code></pre></td></tr></table></figure>

<p>返回值：一个<strong>拒绝值</strong>为这个<strong>入参</strong>的<strong>已拒绝</strong>的<strong>Promise</strong></p>
</li>
<li><p>多个参数</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> p4 = <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(<span class="hljs-number">1</span>,<span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">()=&gt;</span>&#123;&#125;),<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>());<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(p4)  <span class="hljs-comment">// Promise &#123; 1 &#125;</span><br></code></pre></td></tr></table></figure>

<p>返回值：把第一个参数按照上述规则包装返回</p>
</li>
</ul>
<h3 id="Promise-race-、Promise-all"><a href="#Promise-race-、Promise-all" class="headerlink" title="Promise.race()、Promise.all()"></a>Promise.race()、Promise.all()</h3><p>Promise 类提供两个将多个期约实例组合成一个期约的静态方法：Promise.all()和 Promise.race()。而合成后期约的行为取决于内部期约的行为。</p>
<ul>
<li><p>入参：包含promise的可迭代对象（一般就是promise数组）</p>
</li>
<li><p>返回值：一个promise</p>
</li>
<li><p>状态改变：</p>
<ul>
<li>promise.race([xxx,xxx])什么时候改变状态，取决于入参哪个先改变状态。</li>
<li>promise.all([xxx,xxx])需要入参的所有promise<strong>都resolved</strong>解决之后才改变，有一个不是的话状态直接转变为rejected、pending</li>
</ul>
</li>
<li><p>应用：</p>
<p>接口超时拒绝</p>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve,reject</span>)=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;假装我是调一个接口&#x27;</span>)<br>    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>        <span class="hljs-comment">// 可能会花费一些时间</span><br>        <span class="hljs-title function_">resolve</span>(<span class="hljs-number">1</span>)<br>    &#125;,<span class="hljs-number">10000</span>)<br>&#125;)<br><br><span class="hljs-keyword">let</span> b = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve,reject</span>)=&gt;</span>&#123;<br>    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>        <span class="hljs-title function_">reject</span>(<span class="hljs-number">1</span>)<br>    &#125;,<span class="hljs-number">2000</span>)<br>&#125;)<br><br><span class="hljs-keyword">let</span> request = <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">all</span>([a,b])<br>request.<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span>=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;接口没超时&#x27;</span>)<br>&#125;，res=&gt;&#123;<br>      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;接口超时&#x27;</span>)       <br>&#125;)<br></code></pre></td></tr></table></figure>

<h2 id="实例方法"><a href="#实例方法" class="headerlink" title="实例方法"></a>实例方法</h2><p>期约实例的方法是连接外部同步代码与内部异步代码之间的桥梁。这些方法可以</p>
<ul>
<li>访问异步操作返回的数据</li>
<li>处理期约成功和失败的结果</li>
<li>连续对期约求值</li>
<li>添加只有期约进入终止状态时才会执行的代码</li>
</ul>
<h3 id="then"><a href="#then" class="headerlink" title=".then()"></a>.then()</h3><p>接收参数：两个，分别是<strong>onResolved</strong>和<strong>onRejected</strong>，分别代表这个Promise状态被解决的时候执行和被拒绝的时候被执行</p>
<p>返回值：一个Promise</p>
<p>入参规则：两个参数都可选。</p>
<ul>
<li>超过两个参数，自动忽略多余参数</li>
<li>入参类型不是函数也会被自动忽略</li>
<li>可以直传递第一个onResolved参数，不填第二个参数，处理成功的情况</li>
<li>但是如果想只传递一个onRejected处理程序，第一个<strong>不能不写</strong>，需要写个占位的空函数或其他无意义的非函数入参。</li>
</ul>
<blockquote>
<p>因为Promise只能转换为最终状态一次，故这两个参数对应的函数操作一定是互斥的。只会执行其中一个</p>
</blockquote>
<p>返回规则：</p>
<ul>
<li>入参两个都没填，就直接返回上一个promise</li>
<li>只传入了解决处理函数，返回一个已解决且解决值为处理函数的返回值的promise，如果处理函数返回值是一个promise，也直接返回这个promise</li>
<li>只传入了<strong>拒绝处理函数</strong>，返回一个已解决且解决值为处理函数的返回值的promise，如果处理函数返回值是一个promise，也直接返回这个promise</li>
</ul>
<blockquote>
<p>没有返回值（就是undefined）和返回显式的基础数据类型一样（包括异常），都是直接包装成一个已解决的并且解决值为这些基础数据类型的promise</p>
<p>onRejected的返回值包装成Promise的规则和onResolved包装规则是一样的</p>
</blockquote>
<h3 id="catch"><a href="#catch" class="headerlink" title=".catch"></a>.catch</h3><p>是onRejected的另一种写法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve,reject</span>)=&gt;</span>&#123;<br>    <span class="hljs-title function_">reject</span>(<span class="hljs-string">&#x27;111&#x27;</span>)<br>&#125;)<br>a.<span class="hljs-title function_">then</span>(<span class="hljs-literal">null</span>,<span class="hljs-function">()=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;啊啊啊，我被拒绝了&#x27;</span>)<br>&#125;)<br><br><span class="hljs-comment">// 等同于</span><br>a.<span class="hljs-title function_">catch</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;啊啊啊，我被拒绝了&#x27;</span>)<br>&#125;)<br></code></pre></td></tr></table></figure>

<h3 id="finally"><a href="#finally" class="headerlink" title=".finally"></a>.finally</h3><p>在promise转换为已拒绝或者已解决时都会执行，一般用于兜底、添加清理代码</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve,reject</span>)=&gt;</span>&#123;<br>    <span class="hljs-title function_">reject</span>(<span class="hljs-string">&#x27;111&#x27;</span>)<br>&#125;)<br><br>a.<span class="hljs-title function_">finally</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;我走进来了，但是不知道是拒绝还是成功后走进来的&#x27;</span>)<br>&#125;)<br></code></pre></td></tr></table></figure>

<blockquote>
<p>.finally的返回规则有些不一样，在大多数情况下（无返回值、已解决期约）它表现为父期约的传递，如果返回的是一个待定的期约，或者 onFinally 处理程序抛出了错误（显式抛出或返回了一个拒绝期约），则会返回相应的期约（待定或拒绝），如下所示：</p>
</blockquote>
<h3 id="非重入promise方法"><a href="#非重入promise方法" class="headerlink" title="非重入promise方法"></a>非重入promise方法</h3><p>是一个概念，当promise状态改变时对应的处理程序，比如onResolve、onRejected、.catch等不是立马被执行的，而是放到一个异步时事件队列中（先进先出），一般要这个队列的事件是在同步代码之后执行。 </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve,reject</span>)=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;第一个promise&#x27;</span>)<br>    <span class="hljs-title function_">resolve</span>(<span class="hljs-number">1</span>)<br>&#125;)<br><span class="hljs-keyword">let</span> b = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve,reject</span>)=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;第二个promise&#x27;</span>)<br>    <span class="hljs-title function_">resolve</span>(<span class="hljs-number">2</span>)<br>&#125;)<br><span class="hljs-comment">// 先执行</span><br>a.<span class="hljs-title function_">then</span>((<span class="hljs-function">(<span class="hljs-params">res</span>)=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;第一个进来的&#x27;</span>)<br>&#125;))<br><span class="hljs-comment">// 后执行</span><br>b.<span class="hljs-title function_">then</span>((<span class="hljs-function">(<span class="hljs-params">res</span>)=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;第二个进来的&#x27;</span>)<br>&#125;))<br><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;hhhh&#x27;</span>)<br><br><span class="hljs-comment">// 第一个promise</span><br><span class="hljs-comment">// 第二个promise                                   </span><br><span class="hljs-comment">// hhhh                                            </span><br><span class="hljs-comment">// 第一个进来的                                    </span><br><span class="hljs-comment">// 第二个进来的</span><br></code></pre></td></tr></table></figure>
















                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/blog/categories/%E5%89%8D%E7%AB%AF%E6%8A%80%E6%9C%AF%E6%A0%88/" class="category-chain-item">前端技术栈</a>
  
  
    <span>></span>
    
  <a href="/blog/categories/%E5%89%8D%E7%AB%AF%E6%8A%80%E6%9C%AF%E6%A0%88/js/" class="category-chain-item">js</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/blog/tags/js/">#js</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>异步编程（一）Promise</div>
      <div>https://airfe.gitee.io/blog/2023/05/17/异步编程（一）Promise/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Airfe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年5月17日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/blog/2023/05/17/JavaScript%E5%87%BD%E6%95%B0%EF%BC%88%E4%BA%94%EF%BC%89%E7%AB%8B%E5%8D%B3%E8%B0%83%E7%94%A8%E7%9A%84%E5%87%BD%E6%95%B0%E8%A1%A8%E8%BE%BE%E5%BC%8F/" title="JavaScript函数（五）立即调用的函数表达式">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">JavaScript函数（五）立即调用的函数表达式</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/blog/2023/05/13/JavaScript%E5%87%BD%E6%95%B0%EF%BC%88%E5%9B%9B%EF%BC%89%E9%97%AD%E5%8C%85/" title="JavaScript函数（四）闭包">
                        <span class="hidden-mobile">JavaScript函数（四）闭包</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","appKey":"P5fzMTGSJIoTaGvmgzsUHeNZ","path":"window.location.pathname","placeholder":"发表你的看法吧~","avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false,"appid":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","appkey":"P5fzMTGSJIoTaGvmgzsUHeNZ","server_url":"https://rw68dmke.lc-cn-n1-shared.com"},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
        <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> <div style="font-size: 0.85rem"> <span id="timeDate">载入天数</span> <span id="times">载入时分秒</span> <script src="js/duration.js"></script> </div> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="leancloud-site-pv-container" style="display: none">
        总访问量 
        <span id="leancloud-site-pv"></span>
         次
      </span>
    
    
      <span id="leancloud-site-uv-container" style="display: none">
        总访客数 
        <span id="leancloud-site-uv"></span>
         人
      </span>
    
    

  
</div>

  
  
    <!-- 备案信息 ICP for China -->
    <div class="beian">
  <span>
    <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
      蜀ICP备2023008943号
    </a>
  </span>
  
    
      <span>
        <a
          href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=https://beian.miit.gov.cn/"
          rel="nofollow noopener"
          class="beian-police"
          target="_blank"
        >
          
            <span style="visibility: hidden; width: 0">|</span>
            <img src="" srcset="/blog/img/loading.gif" lazyload data-original="/blog/img/police_beian.png" alt="police-icon"/>
          
          <span>京公网安备12345678号</span>
        </a>
      </span>
    
  
</div>

  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/blog/js/events.js" ></script>
<script  src="/blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script defer src="/blog/js/leancloud.js" ></script>

  <script  src="/blog/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>

        <style>
            [bg-lazy] {
                background-image: none !important;
                background-color: #eee !important;
            }
        </style>
        <script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(r){r.imageLazyLoadSetting.processImages=t;var e=r.imageLazyLoadSetting.isSPA,n=r.imageLazyLoadSetting.preloadRatio||1,c=a();function a(){var t=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")),e=Array.prototype.slice.call(document.querySelectorAll("[bg-lazy]"));return t.concat(e)}function t(){e&&(c=a());for(var t,o=0;o<c.length;o++)0<=(t=(t=c[o]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(r.innerHeight*n||document.documentElement.clientHeight*n)&&function(){var t,e,n,a,i=c[o];e=function(){c=c.filter(function(t){return i!==t}),r.imageLazyLoadSetting.onImageLoaded&&r.imageLazyLoadSetting.onImageLoaded(i)},(t=i).hasAttribute("bg-lazy")?(t.removeAttribute("bg-lazy"),e&&e()):(n=new Image,a=t.getAttribute("data-original"),n.onload=function(){t.src=a,t.removeAttribute("data-original"),e&&e()},t.src!==a&&(n.src=a))}()}function i(){clearTimeout(t.tId),t.tId=setTimeout(t,500)}t(),document.addEventListener("scroll",i),r.addEventListener("resize",i),r.addEventListener("orientationchange",i)}(this);</script></body>
</html>
